<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul{
            position:relative;
            width:400px;
            height:50px;
        }
        li{
            float:left;
            width:30px;
            height:30px;
            line-height:30px;
            list-style:none;
            border:1px solid #f0f;
            border-radius:3px;
            box-sizing:border-box;
            margin:0 10px;
            text-align:center;
            cursor:pointer;
        }
    </style>
</head>
<body>
<ul id="ul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
<p id="contxt"></p>
</body>
<script>
    var ul = document.getElementById('ul')
    var li = ul.getElementsByTagName('li')
    var contxt = document.getElementById('contxt')

    /*
        //方法一
        for(var i=0;i<li.length;i++){
            (function(j){
                li[j].onclick=function(){
                    contxt.innerHTML = j
                }
            })(i);
        }



        //方法二
        for(var i=0;i<li.length;i++){
                li[i].index=i
                li[i].onclick=function(){
                    contxt.innerHTML = this.index
                }

        }

    */




    ul.onclick=function(e) {
        var ev = ev || window.event;
        var target = ev.target || ev.srcElement;
        if (target.nodeName.toLowerCase() == "li") {
            var li = this.querySelectorAll("li");
            var index = Array.prototype.indexOf.call(li, target);
            contxt.innerHTML = index
        }

    }



</script>
</html>